/**
 * Copyright (C) 2012-2013 jumei, Inc.
 * RpcProxyFactoryBean.java
 * 2015年6月24日
 */
package com.goface.rpc.conf.parse;

import java.lang.reflect.Proxy;

import org.goface.rpc.ClientProxyBeanInvocationHandler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import com.goface.rpc.conf.DefaultServiceConfigureCenter;
import com.goface.rpc.conf.ServiceConfigure;
import com.goface.rpc.conf.ServiceConfigureCenter;

/**
 *
 * @author jm110
 */
public class RpcBeanPostProcessor implements BeanPostProcessor {

    /*
     * (non-Javadoc)
     *
     * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization(java.lang.Object,
     * java.lang.String)
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        ServiceConfigureCenter configureCenter = DefaultServiceConfigureCenter.getInstance();
        ServiceConfigure serviceconfigure = configureCenter.getServiceConfigure(beanName);
        if (serviceconfigure == null) {
            throw new BeanDefinitionStoreException("can not find configure for bean:" + beanName);
        }
        if (serviceconfigure.isClientService()) {
            String intf = serviceconfigure.getProperty(ServiceConfigure.SERVICE_CLIENT_INTF).toString();
            Class<?> clazz = null;
            try {
                clazz = Class.forName(intf);
            } catch (ClassNotFoundException e) {
                throw new BeanDefinitionStoreException("can not find bean class:" + intf);
            }
            Object clientProxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                    new Class<?>[] { clazz }, new ClientProxyBeanInvocationHandler(serviceconfigure.getId(),
                            configureCenter));
            return clientProxy;
        }
        // server service直接return 原始的spring bean
        return bean;
    }

    /*
     * (non-Javadoc)
     *
     * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization(java.lang.Object,
     * java.lang.String)
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
